package com.wlb365.financing.modules.trade.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Maps;
import com.wlb365.financing.common.constants.ApiConstants;
import com.wlb365.financing.common.constants.SysConstant;
import com.wlb365.financing.common.exception.AdminException;
import com.wlb365.financing.common.utils.ShiroUtil;
import com.wlb365.financing.modules.trade.request.QueryBankListReq;
import com.wlb365.financing.modules.trade.request.VoucherDetailReq;
import com.wlb365.financing.modules.trade.request.VoucherGenerateReq;
import com.wlb365.financing.modules.trade.request.VoucherPageReq;
import com.wlb365.financing.modules.trade.request.VoucherPreviewReq;
import com.wlb365.financing.modules.trade.request.data.QuerySchemaByBtypeReq;
import com.wlb365.financing.modules.trade.request.data.QuerySchemaPageReq;
import com.wlb365.financing.modules.trade.request.voucher.CancelVoucherReq;
import com.wlb365.financing.modules.trade.request.voucher.VoucherAuditDto;
import com.wlb365.financing.modules.trade.request.voucher.VoucherAuditReq;
import com.wlb365.financing.modules.trade.request.voucher.VoucherUpdateReq;
import com.wlb365.financing.modules.trade.response.OrgDataDto;
import com.wlb365.financing.modules.trade.response.QueryBankListRes;
import com.wlb365.financing.modules.trade.response.VoucherDetailRes;
import com.wlb365.financing.modules.trade.response.VoucherGenerateRes;
import com.wlb365.financing.modules.trade.response.VoucherPreviewRes;
import com.wlb365.financing.modules.trade.response.VoucherQueryRes;
import com.wlb365.financing.modules.trade.response.data.QuerySchemaByBtypeRes;
import com.wlb365.financing.modules.trade.response.data.QuerySchemaPageRes;
import com.wlb365.financing.modules.trade.response.voucher.CancelVoucherRes;
import com.wlb365.financing.modules.trade.response.voucher.VoucherAuditRes;
import com.wlb365.financing.common.utils.SdkHelper;
import com.wlb365.financing.modules.trade.response.voucher.VoucherUpdateRes;
import com.wlb365.financing.modules.trade.service.IVoucherService;
import com.wlb365.financing.modules.trade.vo.TemplateVO;
import com.wlb365.financing.modules.trade.vo.VoucherQueryVO;
import com.wlb365.sdk.model.CommonRequest;
import com.wlb365.sdk.model.CommonResponse;
import org.checkerframework.checker.units.qual.C;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 凭证服务实现类.
 *
 * @author zwh
 * @version 1.0
 */
@Service
public class VoucherServiceImpl implements IVoucherService {

    @Override
    public VoucherQueryRes page (final VoucherQueryVO queryVO) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("current", queryVO.getCurrent());
        params.put("size", queryVO.getSize());
        params.put("id", queryVO.getId());
        params.put("contractNo", queryVO.getContractNo());
        params.put("status", queryVO.getStatus());
        params.put("supplierId", queryVO.getSupplierId());
        params.put("coreEnterpriseId", queryVO.getCoreEnterpriseId());
        params.put("createDate", queryVO.getCreateDate());
        return SdkHelper.execute(new VoucherPageReq(), params);
    }

    @Override
    public VoucherDetailRes detail (final String id) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("voucherId", id);
        return SdkHelper.execute(new VoucherDetailReq(), params);
    }

    @Override
    public VoucherPreviewRes voucherPreview (final String tradeId, final String templateId, final String ids) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("templateId", templateId);
        params.put("tradeId", tradeId);
        params.put("ids", ids);
        return SdkHelper.execute(new VoucherPreviewReq(), params);
    }

    @Override
    public List<TemplateVO> queryTemplateList(String compId) {
        //查询核心企业关联的银行列表
        Map<String, Object> params = Maps.newHashMap();
        params.put("compId", compId);
        params.put("compType", SysConstant.DEPT_TYPE_2);
        QueryBankListRes bankListRes = SdkHelper.execute(new QueryBankListReq(), params);
        List<TemplateVO> templateList = new ArrayList<>();
        if (ApiConstants.SUCCESS_CODE.equals(bankListRes.getCode()) && CollectionUtil.isNotEmpty(bankListRes.getItems())) {
            List<String> bankCompIds = bankListRes.getItems().stream().map(OrgDataDto::getId).collect(Collectors.toList());
            //查询用户订阅的模板
            bankCompIds.stream().forEach(id -> {
                Map<String, Object> ptParam = Maps.newHashMap();
                ptParam.put("templateBtype", "voucherInfo");
                ptParam.put("subscribeBy", id);
                QuerySchemaPageRes res = SdkHelper.execute(new QuerySchemaPageReq(), ptParam);
                if (ApiConstants.SUCCESS_CODE.equals(res.getCode()) && CollectionUtil.isNotEmpty(res.getRecords())) {
                    //if ("1".equals(res.getTemplateType())) {
                        //用户模板
                        TemplateVO vo = new TemplateVO();
                        BeanUtil.copyProperties(res.getRecords().get(0), vo);
                        vo.setBankId(id);
                        templateList.add(vo);
                    //}
                }
            });
        }

        //查询平台模板
        Map<String, Object> ptParam = Maps.newHashMap();
        ptParam.put("templateType", "0");
        ptParam.put("templateBtype", "voucherInfo");
        QuerySchemaPageRes res = SdkHelper.execute(new QuerySchemaPageReq(), ptParam);
        if (ApiConstants.SUCCESS_CODE.equals(res.getCode()) && CollectionUtil.isNotEmpty(res.getRecords())) {
            TemplateVO vo = new TemplateVO();
            BeanUtil.copyProperties(res.getRecords().get(0), vo);
            templateList.add(vo);
        }
        return templateList;
    }

    @Override
    public QueryBankListRes queryBankList(final String compId){
        Map<String, Object> params =  Maps.newHashMap();
        params.put("compId", compId);
        params.put("compType", SysConstant.DEPT_TYPE_2);
        QueryBankListRes res = SdkHelper.execute(new QueryBankListReq(), params);
        //查询无用户模板银行
        res.getItems().stream().forEach(x -> {
            Map<String, Object> ptParam = Maps.newHashMap();
            ptParam.put("templateBtype", "voucherInfo");
            ptParam.put("subscribeBy", x.getId());
            QuerySchemaPageRes r = SdkHelper.execute(new QuerySchemaPageReq(), ptParam);
            if (ApiConstants.SUCCESS_CODE.equals(r.getCode()) && CollectionUtil.isNotEmpty(r.getRecords())) {
                if ("1".equals(r.getRecords().get(0).getTemplateType())) {
                    x.setSelected(false);//有用户模板的不可选择
                }
            }
        });

        return res;
    }

    @Override
    public VoucherGenerateRes generate (final String tradeId, final String templateId, final String bankId, final String ids) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("templateId", templateId);
        params.put("tradeId", tradeId);
        params.put("bankId", bankId);
        params.put("createBy", ShiroUtil.getUserId());
        params.put("ids", ids);
        VoucherGenerateRes res = SdkHelper.execute(new VoucherGenerateReq(), params);
        if (!ApiConstants.SUCCESS_CODE.equals(res.getCode())) {
            throw new AdminException("凭证生成失败， " + res.getMsg() + ": " + res.getSubMsg());
        }
        return res;
    }

    @Override
    public VoucherAuditRes audit (final String id, final String status, final String remark) {
        VoucherAuditDto dto = new VoucherAuditDto();
        dto.setVoucherId(id);
        dto.setStatus(status);
        dto.setRemark(remark);
        dto.setCreateBy(String.valueOf(ShiroUtil.getUserId()));
        dto.setCompId(String.valueOf(ShiroUtil.getUser().getDeptId()));
        VoucherAuditReq req = new VoucherAuditReq();
        req.setBizModel(dto);
        return SdkHelper.execute(req);
    }

    @Override
    public VoucherUpdateRes updateSign (final String id, final String flowId) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("voucherId", id);
        params.put("flowId", flowId);
        params.put("nextStatus", true);
        return SdkHelper.execute(new VoucherUpdateReq(), params);
    }
//
//    @Override
//    public UpdateVoucherStatusRes updateVoucherStatus(final String id, final String status, final String sign) {
//        Map<String, Object> params = Maps.newHashMap();
//        params.put("voucherId", id);
//        if (!StringUtils.isEmpty(status)) {
//            params.put("status", status);
//        }
//        if (!StringUtils.isEmpty(sign)) {
//            params.put("sign", sign);
//        }
//        return SdkHelper.execute(new UpdateVoucherStatusReq(), params);
//    }

    @Override
    public CancelVoucherRes cancelVoucher(final String id) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("voucherId", id);
        return SdkHelper.execute(new CancelVoucherReq(), params);
    }

    @Override
    public VoucherUpdateRes update(final String id, final String bankId, final String sign, final boolean nextStatus) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("voucherId", id);
        params.put("bankId", bankId);
        params.put("sign", sign);
        params.put("nextStatus", nextStatus);
        return SdkHelper.execute(new VoucherUpdateReq(), params);
    }

    @Override
    public CommonResponse send(String id, String bankId) {
        CommonRequest req = new CommonRequest("fs.voucher.send");
        Map<String, Object> params = new HashMap<>();
        params.put("voucherId", id);
        params.put("bankId", bankId);
        req.setBizModel(params);
        return SdkHelper.executeAndCheck(req);
    }
}
